package com.gengzp.common.utils;

import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName RedisUtils
 * @Description redis工具类
 * @Author gengzp
 * @Date 2025/9/8 14:49
 */
@Data
@Component
public class RedisUtils {

    private static final Logger logger = LoggerFactory.getLogger(RedisUtils.class);

    private static RedisTemplate<String, Object> redisTemplateInstance;

    private RedisUtils(RedisTemplate<String, Object> redisTemplate) {
        redisTemplateInstance = redisTemplate;
    }

    // ===================== 通用操作 =====================

    /**
     * 设置过期时间
     *
     * @param key  键
     * @param time 过期时间(秒)
     */
    public static void expire(String key, Long time) {
        redisTemplateInstance.expire(key, time, TimeUnit.SECONDS);
    }

    /**
     * 删除缓存中的key
     *
     * @param key 键
     */
    public static void del(String key) {
        redisTemplateInstance.delete(key);
    }

    // ===================== String操作 =====================

    /**
     * 存入字符串数据, 并指定过期时间
     *
     * @param key   键
     * @param value 值
     * @param time  缓存时间(秒)
     */
    public static void set(String key, String value, Long time) {
        redisTemplateInstance.opsForValue().set(key, value, time, TimeUnit.SECONDS);
    }

    /**
     * 根据键获取字符串
     *
     * @param key 键
     * @return 值
     */
    public static String get(String key) {
        try {
            return String.valueOf(redisTemplateInstance.opsForValue().get(key));
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 存入字符串数据, 如果键已存在, 则返回false
     *
     * @param key   键
     * @param value 值
     * @param time  缓存时间(秒)
     * @return 是否成功
     */
    public static Boolean setIfAbsent(String key, String value, Long time) {
        return redisTemplateInstance.opsForValue().setIfAbsent(key, value, time, TimeUnit.SECONDS);
    }

    /**
     * 执行Lua脚本, 无返回值
     *
     * @param script Lua脚本
     * @param keys   键列表
     * @param args   参数列表
     */
    public static void eval(String script, List<String> keys, List<String> args) {
        try {
            redisTemplateInstance.execute(RedisScript.of(script, Long.class), keys, args);
        } catch (Exception e) {
            logger.error("执行Lua脚本失败: {}", script, e);
            throw e;
        }
    }

}
